package conf

import (
    "flag"
    "os"
    "gougouapi/core/logger"
    "gopkg.in/yaml.v2"
    "io/ioutil"
    "gopkg.in/redis.v4"
    "gougouapi/variables"
)

var (
    configFile *string
    Config  *ConfigModel = new(ConfigModel)
)

type ConfigModel struct {
    Addr    string
    Mysql   struct{
        Host        string
        Port        int
        User        string
        Password    string
        DbName      string
            }

    Redis   struct{
        Addr        string
        Password    string
        DB          int
            }

    App     variables.App
}

func init() {
    configFile = flag.String("config-file", "./config/config.yml", "配置文件地址")
    flag.Parse()

    parseConfig()
}

func parseConfig() {
    file, err := os.OpenFile(*configFile, os.O_RDONLY, 0444)
    if err != nil {
        logger.Main.Fatalln(err)
    }
    if configBytes, err := ioutil.ReadAll(file); err != nil {
        logger.Main.Fatalln(err)
    } else {
        yaml.Unmarshal(configBytes, Config)
    }

    variables.RedisClient = redis.NewClient(&redis.Options{
        Addr: Config.Redis.Addr,
        Password: Config.Redis.Password,
        DB: Config.Redis.DB,
    })
    variables.MysqlConfig.Host = Config.Mysql.Host
    variables.MysqlConfig.Port = Config.Mysql.Port
    variables.MysqlConfig.User = Config.Mysql.User
    variables.MysqlConfig.Password = Config.Mysql.Password
    variables.MysqlConfig.DbName = Config.Mysql.DbName

    variables.AppConfig = Config.App
}
